<template>
  <div class="sales-return-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>销售退货</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="退货单号">
            <el-input
              v-model="searchForm.orderCode"
              placeholder="请输入退货单号"
              clearable
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="单据状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="客户名称">
            <el-select
              v-model="searchForm.customerId"
              placeholder="请选择客户"
              clearable
              filterable
              style="width: 200px"
              :loading="customerLoading"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="退货日期">
            <el-date-picker
              v-model="searchForm.returnDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 160px"
              clearable
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-card class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">销售退货列表</div>
            <div class="table-actions">
              <el-button type="success" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                新增
              </el-button>
              <el-button type="danger" plain :disabled="!selectedRows.length" @click="handleBatchDelete">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
              <el-button plain :disabled="!selectedRows.length" @click="handleCopy">
                复制
              </el-button>
              <el-button type="primary" plain :disabled="!selectedRows.length" @click="handleApprove">
                审核
              </el-button>
              <el-button plain :disabled="!selectedRows.length" @click="handleRevoke">
                撤销
              </el-button>
              <el-button plain :disabled="!selectedRows.length" @click="handleClose">
                关闭
              </el-button>
              <el-button plain @click="handleExport">
                导出
              </el-button>
              <el-button type="primary" @click="handleRefresh" :loading="loading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :height="tableHeight"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />

          <el-table-column prop="orderCode" label="退货单号" width="160" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link type="primary" @click="handleViewDetail(row)">
                {{ row.orderCode || '-' }}
              </el-link>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="单据状态" width="110">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ row.statusName || getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="returnDate" label="退货日期" width="130">
            <template #default="{ row }">
              {{ formatDate(row.returnDate, 'date') }}
            </template>
          </el-table-column>

          <el-table-column prop="salesOrderItemCode" label="销售单号" width="160" show-overflow-tooltip />
          <el-table-column prop="customerName" label="客户名称" width="140" show-overflow-tooltip />
          <el-table-column prop="contact" label="联系人" width="110" show-overflow-tooltip />
          <el-table-column prop="contactPhone" label="联系方式" width="140" />
          <el-table-column prop="auditor" label="销售负责人" width="120" show-overflow-tooltip />

          <el-table-column prop="totalQuantity" label="退货数量" width="110" align="right">
            <template #default="{ row }">
              {{ row.totalQuantity ?? 0 }}
            </template>
          </el-table-column>

          

          <el-table-column prop="returnGoods" label="退货商品" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              {{ formatGoods(row.returnGoods) }}
            </template>
          </el-table-column>

          <el-table-column prop="customerName" label="制单人" width="110" show-overflow-tooltip />

          <el-table-column prop="createTime" label="制单时间" width="170">
            <template #default="{ row }">
              {{ formatDate(row.createTime, 'datetime') }}
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right" width="140">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const router = useRouter()

const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

const customerList = ref([])
const customerLoading = ref(false)

const searchForm = reactive({
  orderCode: '',
  status: '',
  customerId: '',
  returnDate: ''
})

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

const statusOptions = [
  { label: '草稿', value: 0 },
  { label: '待审核', value: 1 },
  { label: '已审核', value: 2 },
  { label: '已完成', value: 3 },
  { label: '已关闭', value: 4 }
]

const statusTypeMap = {
  0: 'info',
  1: 'warning',
  2: 'success',
  3: 'primary',
  4: 'danger'
}

const statusTextMap = {
  0: '草稿',
  1: '待审核',
  2: '已审核',
  3: '已完成',
  4: '已关闭'
}

const tableHeight = computed(() => window.innerHeight - 400)

const getStatusType = (status) => statusTypeMap[status] || 'info'
const getStatusText = (status) => statusTextMap[status] || '未知状态'

const formatDate = (value, mode = 'date') => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return value
  }

  const yyyy = date.getFullYear()
  const mm = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')
  const hh = String(date.getHours()).padStart(2, '0')
  const mi = String(date.getMinutes()).padStart(2, '0')
  const ss = String(date.getSeconds()).padStart(2, '0')

  if (mode === 'datetime') {
    return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`
  }

  return `${yyyy}-${mm}-${dd}`
}

const formatAmount = (amount) => {
  if (amount === null || amount === undefined || amount === '') {
    return '0.00'
  }
  const num = Number(amount)
  if (Number.isNaN(num)) {
    return '0.00'
  }
  return num.toFixed(2)
}

const formatGoods = (goods) => {
  if (!goods) return '-'
  const value = typeof goods === 'string' ? goods.trim() : String(goods)
  if (!value) return '-'

  if (value.startsWith('[') || value.startsWith('{')) {
    try {
      const parsed = JSON.parse(value)
      let items = []
      if (Array.isArray(parsed)) {
        items = parsed
      } else if (parsed.items && Array.isArray(parsed.items)) {
        items = parsed.items
      } else if (typeof parsed === 'object') {
        items = [parsed]
      }

      const names = items
        .map((item) => item.goodsName || item.name || item.productName || item.title)
        .filter(Boolean)

      if (names.length === 0) {
        return '-'
      }

      return names.length > 3 ? `${names.slice(0, 3).join('、')}等${names.length}项...` : names.join('、')
    } catch (error) {
      // ignore parse error and fall through
    }
  }

  if (value.length > 40) {
    return `${value.slice(0, 40)}...`
  }
  return value
}

const normalizeRows = (rows = []) => {
  return rows.map((item) => ({
    ...item,
    statusName: item.statusName || getStatusText(item.status)
  }))
}

const fetchCustomerList = async () => {
  customerLoading.value = true
  try {
    const response = await proxy.http.post(
      '/api/customermodel/GetPageData',
      { pageIndex: 1, pageSize: 500 },
      false
    )

    let data = []

    if (response) {
      if (Array.isArray(response.rows)) {
        data = response.rows
      } else if (Array.isArray(response.data?.rows)) {
        data = response.data.rows
      } else if (Array.isArray(response.data?.data)) {
        data = response.data.data
      } else if (Array.isArray(response.data)) {
        data = response.data
      }
    }

    customerList.value = data
      .map((item) => ({
        id: item.Id || item.id,
        name: item.CustomerName || item.customerName || item.name
      }))
      .filter((item) => item.id && item.name)
  } catch (error) {
    console.error('获取客户列表失败:', error)
    ElMessage.error('获取客户列表失败')
    customerList.value = []
  } finally {
    customerLoading.value = false
  }
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }

    if (searchForm.orderCode && searchForm.orderCode.trim() !== '') {
      params.orderCode = searchForm.orderCode.trim()
    }

    if (searchForm.status !== '' && searchForm.status !== null && searchForm.status !== undefined) {
      params.status = Number(searchForm.status)
      if (Number.isNaN(params.status)) {
        delete params.status
      }
    }

    if (searchForm.customerId) {
      params.supplierId = searchForm.customerId
    }

    if (searchForm.returnDate) {
      params.returnDate = searchForm.returnDate
    }

    const response = await proxy.http.get(
      '/api/SalesReturnOrderModel/GetPageList',
      params,
      false
    )

    let rows = []
    let total = 0

    if (response) {
      const success =
        response.success === true ||
        response.status === true ||
        response.status === 1 ||
        response.status === 0 ||
        response.code === 200 ||
        response.code === 0

      if (success) {
        if (Array.isArray(response.data?.rows)) {
          rows = response.data.rows
          total = response.data.total ?? response.data.rows.length ?? 0
        } else if (Array.isArray(response.rows)) {
          rows = response.rows
          total = response.total ?? response.records ?? rows.length
        } else if (Array.isArray(response.data?.data)) {
          rows = response.data.data
          total = response.data.total ?? response.data.count ?? rows.length
        } else if (Array.isArray(response.data)) {
          rows = response.data
          total = response.total ?? rows.length
        } else if (Array.isArray(response.list)) {
          rows = response.list
          total = response.total ?? response.count ?? rows.length
        }
      } else {
        const message = response.msg || response.message || '获取销售退货列表失败'
        ElMessage.error(message)
      }
    }

    tableData.value = normalizeRows(rows)
    pagination.total = total

    if (!rows || rows.length === 0) {
      tableData.value = []
    }
  } catch (error) {
    console.error('获取销售退货列表失败:', error)
    ElMessage.error('获取销售退货列表失败，请稍后重试')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSearch = () => {
  pagination.pageIndex = 1
  fetchData()
}

const handleReset = () => {
  searchForm.orderCode = ''
  searchForm.status = ''
  searchForm.customerId = ''
  searchForm.returnDate = ''
  pagination.pageIndex = 1
  fetchData()
}

const handleRefresh = () => {
  fetchData()
}

const handleAdd = () => {
  router.push('/wms.salesreturnorder/salesreturnorder/add')
}

const handleViewDetail = (row) => {
  ElMessage.info(`查看退货单详情：${row.orderCode}`)
}

const handleEdit = (row) => {
  ElMessage.info(`编辑退货单：${row.orderCode}`)
}

const handleDelete = (row) => {
  if (!row || !row.orderCode) {
    return
  }
  ElMessageBox.confirm(`确定删除退货单【${row.orderCode}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage.success('删除操作暂未接入后端')
    })
    .catch(() => {})
}

const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    return
  }
  ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 条退货单吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage.success('批量删除操作暂未接入后端')
    })
    .catch(() => {})
}

const handleCopy = () => {
  if (!selectedRows.value.length) {
    return
  }
  ElMessage.info('复制功能暂未接入后端')
}

const handleApprove = () => {
  if (!selectedRows.value.length) {
    return
  }
  ElMessage.info('审核功能暂未接入后端')
}

const handleRevoke = () => {
  if (!selectedRows.value.length) {
    return
  }
  ElMessage.info('撤销功能暂未接入后端')
}

const handleClose = () => {
  if (!selectedRows.value.length) {
    return
  }
  ElMessage.info('关闭功能暂未接入后端')
}

const handleExport = () => {
  ElMessage.info('导出功能暂未接入后端')
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchData()
}

const handleCurrentChange = (page) => {
  pagination.pageIndex = page
  fetchData()
}

onMounted(async () => {
  await fetchCustomerList()
  fetchData()
})
</script>

<style scoped>
.sales-return-order-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
}

.table-title {
  display: flex;
  flex-direction: column;
  gap: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

::deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

::deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

::deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

@media (max-width: 1200px) {
  .table-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .table-actions {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .sales-return-order-container {
    padding: 10px;
  }

  .search-form {
    flex-direction: column;
  }
}
</style>

